<script lang="jsx">
import { defineComponent, defineAsyncComponent, h, computed } from 'vue'
import File from './File.vue'
import { showEnumValues, showListValues } from '../utils/table'
import { getTemplateData, getCustomContent } from '../AutoGrid/tool'
import { Icon } from '@/components/Icon'
import { StreamPreview, ContentEditor, FilePreview } from '../components/FilePreview'
import { createImageViewer } from '@/components/ImageViewer'

const modules = import.meta.glob('../../views/**/*.{vue,tsx}')

export default defineComponent({
  name: 'CellRender',
  props: {
    row: {
      type: Object,
      default: () => ({})
    },
    col: {
      type: Object,
      default: () => ({})
    },
    meta: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update'],
  setup(props, {}) {
    const row = computed(() => props.row)
    const col = computed(() => props.col)
    const getPreviewIcon = (type) => {
      switch (type) {
        case 'rtsp':
        case 'video':
        case 'mp4':
          return 'mdi:video'
        case 'yaml':
          return 'logos:yaml'
        case 'json':
          return 'tabler:json'
        case 'image':
        case 'img':
        case 'thumbnail':
          return 'material-symbols:image'
        default:
          return 'ele-View'
      }
    }
    const getPreviewType = (url) => {
      const suffix = url?.split('.')?.reverse()[0]
      if (['jpg', 'jpeg', 'png', 'gif'].includes(suffix)) {
        return 'image'
      } else if (['mp4'].includes(suffix)) {
        return 'mp4'
      } else if (['yaml', 'yml'].includes(suffix)) {
        return 'yaml'
      } else if (['json'].includes(suffix)) {
        return 'json'
      }
    }
    const onEditClosed = (data) => {
      emit('update', data)
    }
    // 内容显示预览
    const contentView = (row, col, content) => {
      // 打开链接
      const previewContent = col.pattern ? getTemplateData(col.pattern, row) : row[col.key]
      // 预览类型
      const previewType = col.preview === true ? getPreviewType(previewContent) : col.preview
      return col.preview && row[col.key] ? (
        <el-link
          class={col.preview}
          onClick={(e) => {
            if (['rtsp', 'video', 'mp4'].includes(previewType) && previewContent) {
              StreamPreview({
                url: previewContent
              })
              e.preventDefault()
              e.stopPropagation()
            } else if (['yaml', 'json'].includes(previewType) && previewContent) {
              ContentEditor({
                type: previewType,
                content: previewContent,
                'onUpdate:content': (content) => {
                  row[col.key] = content
                  onEditClosed({
                    row: row,
                    column: { field: col.key },
                    $table: tableRef.value
                  })
                }
              })
              e.preventDefault()
              e.stopPropagation()
            } else if (['img', 'image', 'thumbnail'].includes(previewType) && previewContent) {
              createImageViewer({
                urlList: [previewContent],
                hideOnClickModal: true
              })
              e.preventDefault()
              e.stopPropagation()
            } else if (previewContent) {
              FilePreview({
                url: previewContent
              })
            }
          }}
        >
          {col.preview === 'thumbnail' ? (
            <img src={previewContent}></img>
          ) : (
            <>
              <Icon class="preview-icon" size={20} icon={getPreviewIcon(previewType)} />
              {['rtsp', 'video', 'mp4'].includes(col.preview) ? '播放' : '查看'}
            </>
          )}
        </el-link>
      ) : (
        content
      )
    }
    if (props.meta) {
      if (props.config?.['edit-config']) {
        // initRemoteValues(props.meta)
        // initAutocomplete(props.meta)
      }
      return () => {
        if (['string', 'enum'].includes(col.value.type) && col.value.key?.includes('.')) {
          return <>{enumForeignValue(row.value, col.value, props.meta)}</>
        }
        switch (col.value.type) {
          case 'file':
            return <File path={row.value[col.value.key]} meta={col.value} />
          case 'fileset':
            return <File paths={row.value[col.value.key]} meta={col.value} />
          case 'route':
            return (
              <router-link
                to={getTemplateData(col.value.pattern || row.value[col.value.key], row.value)}
              >
                <el-link>
                  <Icon icon="uil:link"></Icon>
                  {col.value['custom-content']
                    ? getCustomContent(col.value['custom-content'], row.value)
                    : '链接'}
                </el-link>
              </router-link>
            )
          case 'url':
            return (
              <a
                target="_blank"
                href={getTemplateData(col.value.pattern || row.value[col.value.key], row.value)}
              >
                <Icon icon="uil:link"></Icon>
                {col.value['custom-content']
                  ? getCustomContent(col.value['custom-content'], row.value)
                  : '链接'}
              </a>
            )
          case 'progress':
            return (
              <el-progress
                text-inside={true}
                stroke-width={20}
                {...getTemplateData(col.value.props, row.value)}
                percentage={(() => {
                  if (col.value.props?.percentage) {
                    const rsp = getTemplateData(col.value.props?.percentage, row.value)
                    return Number(rsp) || rsp || 0
                  }
                  return (row.value[col.value.key] && Number(row.value[col.value.key])) || 0
                })()}
              />
            )
          case 'list':
          case 'tree-select-multiple':
            return <>{showListValues(row.value[col.value.key], col.value)}</>
          case 'enum':
          case 'tree-select':
            return <>{showEnumValues(row.value[col.value.key], col.value)}</>
          case 'bool':
            return col.value['custom-content'] ? (
              getCustomContent(col.value['custom-content'], row.value)
            ) : (
              <el-checkbox
                v-model={row.value[col.value.key]}
                disabled={col.value.editable ? false : true}
              />
            )
          case 'dict':
            return contentView(row.value, col, <>{JSON.stringify(row.value[col.value.key])}</>)
          case 'password':
            return <>{`${row.value[col.value.key] ? '******' : ''}`}</>
          case 'color':
            return col.value.editable ? (
              <el-color-picker
                v-model={row.value[col.value.key]}
                onChange={(val) => {
                  console.log(val)
                  onEditClosed({
                    row: row.value,
                    column: { field: col.value.key },
                    $table: tableRef.value
                  })
                }}
              />
            ) : (
              <div class="el-color-picker">
                <div class="el-color-picker__trigger">
                  <span
                    class="el-color-picker__color"
                    style={`background-color: ${row.value[col.value.key]};`}
                  ></span>
                </div>
              </div>
            )
          case 'component':
            // 如果配置了自定义组件，使用自定义组件渲染
            const moduleLoader = modules[`../../views/${col.value.component.module}.vue`]
            if (moduleLoader) {
              const MyAsyncComponent = defineAsyncComponent({
                loader: () => moduleLoader()
              })
              // 渲染异步组件，并传递默认插槽内容
              return h(MyAsyncComponent, {
                key: `${row.value.id}-${col.value.key}-${row.value[col.value.key]}`,
                data: row.value,
                col: col.value,
                meta: props.meta
              })
            }
          default:
            // return <div>{props.row?.[props.col?.key]}</div>
            return contentView(
              row.value,
              col.value,
              <>
                {col.value['custom-content']
                  ? getCustomContent(col.value['custom-content'], row.value)
                  : typeof row[col.value.key] === 'object'
                  ? JSON.stringify(row.value[col.value.key])
                  : row.value[col.value.key]}
              </>
            )
        }
      }
    }
    return {}
  }
})
</script>
<style lang="less">
.vxe-select--panel.is--transfer {
  z-index: 3001 !important;
}
.vxe-table {
  .vxe-body--column.preview-thumbnail {
    & > .vxe-cell {
      height: 100%;
    }
    .el-link {
      width: 100%;
      height: 100%;
      .el-link__inner {
        width: 100%;
        height: 100%;
      }
      img {
        width: auto;
      }
    }
  }
}
</style>
